package com.demo.controller;

import com.demo.entity.CartInfoList;
import com.demo.entity.Cartitem;
import com.demo.entity.Message;
import com.demo.entity.Products;
import com.demo.service.CartitemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Controller					//加入IOC容器
@RequestMapping("controller")
public class  CartitemController{
	//控制器依赖于Service
	@Autowired
	@Qualifier("cartitemService")
	private CartitemService cartitemService;
	public void setCartitemService(CartitemService cartitemService) {
		this.cartitemService = cartitemService;
	}

	//查询所有商品信息列表
	@RequestMapping("cart_list_action")
	public String queryAllProdectsInfo(HttpServletRequest request){
		String uname = (String) request.getSession().getAttribute("USERNAME");
		System.out.println("uname===============:"+uname);
		List<CartInfoList> cartitemList = cartitemService.queryCartitemInfo(uname);
		System.out.println("cartitemList:"+cartitemList);
		for(CartInfoList car:cartitemList){
			System.out.println("+++++++"+car.getP_name()+car.getP_price()+car.getP_buynum());
		}
		request.getSession().setAttribute("cartInfoList", cartitemList);
		return "redirect:/views/cart_list.jsp";
	}

	//加入购物车
	@SuppressWarnings("finally")
	@RequestMapping("addCartitemInfo/{product_id}")
	public String addCartitemInfo(@PathVariable("product_id")String product_id,HttpServletRequest request){

		String username = (String) request.getSession().getAttribute("USERNAME");
		System.out.println("username:"+username+"\tproduct_id:"+product_id);
		//先查询buynum的值再判断,查到数据时更新值+1，查不到时报异常，执行增加操作
		Cartitem cartitem = cartitemService.selectCartInfoByProductId(product_id);
		System.out.println("先查询buynum的值再判断--------------------");
		if(cartitem != null){
			cartitemService.updateCartByProductId(product_id,1);
			System.out.println("update-----------------------");
		}else{
			cartitemService.addCartInfoByProductId(username,product_id,1);
			System.out.println("add----------------------");
		}
		System.out.println("成功加入购物车...");
		request.getSession().setAttribute("msgCartTF","加入成功");
		return "redirect:/controller/product_list_page_action";
	}

	//显示商品详细信息并可添加至购物车
	@RequestMapping({"detailCartitemInfo/{productId}","detailCartOrdersInfo/{productId}","ordersInfoByAdmin/{productId}"})
	public void showDetailCartitemInfo(@PathVariable("productId")int productId,HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		//调用函数-根据商品号返回商品对象
		Products products = getProducts(productId,req);
		if(products != null){
			HttpSession session = req.getSession();
			session.setAttribute("products", products);
			System.out.println("根据ID获取商品对象++++++++++");
			String uri = req.getRequestURI();
			if(uri.endsWith("/detailCartitemInfo/"+productId)){
				System.out.println("重定向到商品详细信息页。。。。。。。。。。");
				//根据商品查询留言信息并显示
				List<Message> messageInfo = cartitemService.queryMessageById(Integer.toString(productId));
				System.out.println("留言信息显示成功..............");
				req.getSession().setAttribute("messageInfo", messageInfo);
				resp.sendRedirect("/WebStoreSSM/views/product_list_detail.jsp");
			}else if(uri.endsWith("/detailCartOrdersInfo/"+productId)){
				System.out.println("重定向到下单详细信息页。。。。。。。。。。");
				resp.sendRedirect("/WebStoreSSM/views/orders.jsp");
			}else if(uri.endsWith("/ordersInfoByAdmin/"+productId)){
				System.out.println("重定向到下单详细信息页。。。。。。。。。。");
				resp.sendRedirect("/WebStoreSSM/views/orderByAdmin.jsp");
			}
		}else{
			System.out.println("显示商品详细信息失败XXXXXXXXXXXXX");
		}
	}
	//根据商品号返回商品对象
	private Products getProducts(int productId,HttpServletRequest req) {
		HttpSession session = req.getSession();
		List<Products> productsList = (ArrayList<Products>) session.getAttribute("productsInfoList");
		if(productsList == null){
			System.out.println("productsList------------------");
			return null;
		}
		for (Products productsInfoList : productsList) {
			if(productsInfoList.getProduct_id() == productId){
				return productsInfoList;
			}
		}
		return null;
	}

	//根据用户输入数量将对应的商品加入购物车
	@RequestMapping("addProductsNumById")
	public String addProductsNumById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
		String product_id = req.getParameter("id");
		int quantity = Integer.parseInt(req.getParameter("quantity"));
		System.out.println(product_id+"  -------------------------  "+quantity);
		//根据用户输入数量quantity将对应的商品加入购物车
		String username = (String) req.getSession().getAttribute("USERNAME");
		System.out.println("username:"+username+"\tproduct_id:"+product_id);
		//先查询buynum的值再判断,查到数据时更新值+1，查不到时报异常，执行增加操作
		Cartitem cartitem = cartitemService.selectCartInfoByProductId(product_id);
		if(cartitem != null){
			cartitemService.updateCartByProductId(product_id,quantity);
		}else{
			cartitemService.addCartInfoByProductId(username,product_id,quantity);
		}
		System.out.println("成功加入购物车...");
		req.getSession().setAttribute("succMsg","加入成功");
		return "product_list_detail";
	}

	//删除购物车商品
	@RequestMapping("deleteCartInfoByProductsName/{productsName}")
	public String DeleteCartInfoByProductsName(@PathVariable("productsName")String productsName,HttpServletRequest request){
		System.out.println("删除操作......................");
		cartitemService.deleteCartInfoByProductsName(productsName);
		System.out.println("删后再查.....................");
		return queryAllProdectsInfo(request);
	}
	//修改购物车商品数量前的准备
	@RequestMapping("changeCartInfoByProductsName/{productsName}")
	public String ChangeCartProductNum(@PathVariable("productsName")String productsName,HttpServletRequest req) throws UnsupportedEncodingException{
		List<CartInfoList> cartInfo = (ArrayList<CartInfoList>) req.getSession().getAttribute("cartInfoList");
		CartInfoList carChInfo = new CartInfoList();
		for (CartInfoList cartInfoList : cartInfo) {
			if(cartInfoList.getP_name().equals(productsName)){
				carChInfo.setP_name(productsName);
				carChInfo.setP_price(cartInfoList.getP_price());
				carChInfo.setP_buynum(cartInfoList.getP_buynum());
			}
		}
		req.getSession().setAttribute("carChInfo", carChInfo);
		return "cart_list_detail";
	}
	//修改购物车商品数量
	@RequestMapping("changeCartProductNum")
	public String ChangeCartProductNum(HttpServletRequest req) throws UnsupportedEncodingException{
		int cnum = Integer.parseInt(req.getParameter("changeNum"));		//获取修改后的数量值
		String pname = new String(req.getParameter("pname").getBytes("iso-8859-1"),"UTF-8");
		System.out.println("cnum:"+cnum+"pname:"+pname);
		cartitemService.updateCartProductNum(cnum, pname);
		System.out.println("修改购物车商品数量cg..........");
		return queryAllProdectsInfo(req);
	}

}